package club.pinea.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author pineapple
 * @date 2017年12月26日 下午1:29:36
 * @description 服务器端
 */
//@Configuration
public class LobbyServer implements Runnable {

    Logger logger = LoggerFactory.getLogger(LobbyServer.class);

    @Autowired
    private LobbyServerInitializer lobbyServerInitializer;

    @Value("${server.lobby.port}")
    public Integer lobbyPort;

    /**
     * 创建服务端线程组并绑定端口
     *
     * @throws Exception
     */
    @Override
    public void run() {
        //用于监测客户端连接的线程池
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //工作的线程池
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            //将两个线程组绑定到引导程序并添加参数
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(lobbyServerInitializer);
            //绑定端口, 同步等待成功;
            ChannelFuture future = bootstrap.bind(lobbyPort).sync();
            logger.info("大厅服务器启动成功，端口：" + lobbyPort);
            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //优雅关闭 线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
